/*
 * @Author: MarioGo
 * @Date: 2021-11-12 10:11:02
 * @LastEditTime: 2021-11-20 14:43:55
 * @LastEditors: MarioGo
 * @Description: 文件描述
 * @FilePath: /zheye/src/api/service.ts
 * 可以输入预定的版权声明、个性签名、空行等
 */
import axios from 'axios';
import store from '../store';
// import qs from 'qs';
// import { getToken } from '../utils/util';

axios.defaults.baseURL = 'http://yapi.52react.cn/mock/14/vuex';
axios.defaults.timeout = 6000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    //新增 stroe loading显示
    store.commit('setLoading', true);
    return config;
  },
  (error) => {
    store.commit('setError', { status: false, message: '' });
    return Promise.reject(error);
  },
);
// 响应拦截  异常处理
axios.interceptors.response.use(
  (response) => {
    //新增 stroe loading隐藏
    store.commit('setLoading', false);
    return response.data;
  },
  (e) => {
    const { error } = e.response.data;
    store.commit('setError', { status: true, message: error });
    store.commit('setLoading', false);
    console.log('object :>> ', error);
  },
);
// todo:扩展
export default {
  async get(url: string, params?: any) {
    return new Promise((resolve, reject) => {
      try {
        axios.get(url, params).then((res) => {
          resolve(res);
        });
      } catch (error) {
        reject(error);
      }
    });
  },
  async post(url: string, params?: any, config?: any) {
    return new Promise((resolve, reject) => {
      try {
        axios.post(url, params, config).then((res) => {
          resolve(res);
        });
      } catch (error) {
        reject(error);
      }
    });
  },
};
